<template>
  <view class="publish-bg">
    <view class="form-section">
      <!-- 内容输入框 -->
      <u-input v-model="form.content" type="textarea" placeholder="记录此时此刻..." class="content-input dark-input" :border="false" />
      <!-- 图片预览区域 -->
      <view class="image-preview" v-if="imageUrls.length > 0">
        <view class="preview-item" v-for="(url, index) in imageUrls" :key="index">
          <image :src="globalConfig.site_url +url" mode="aspectFill" class="preview-img" />
          <view class="delete-img-btn" @click="deleteImage(index)">
            <u-icon name="close" size="22" color="#fff" />
          </view>
        </view>
      </view>
      <!-- 城市选择、图片、表情、开关 -->
      <view class="form-row">
        <view class="city-tag" @click="chooseCity">
          <u-icon name="map" size="20" color="#7bdffe" />
          <text>{{ cityName || '北京市' }}</text>
          </view>
        <view class="icon-btn" @click="chooseImage">
          <u-icon name="photo" size="24" color="#fff" />
        </view>
        <!-- <view class="icon-btn" @click="chooseEmoji">
          <u-icon name="smile" size="24" color="#fff" />
        </view> -->
        <view class="switch-box">
          <u-switch v-model="form.visible" activeColor="#007aff" inactiveColor="#23232b" />
          <text class="switch-label">广场可见</text>
        </view>
      </view>
      <!-- 发布按钮 -->
      <view class="publish-btn-box">
        <u-button type="primary" shape="circle" @click="submit" :loading="isSubmitting" :disabled="isSubmitting" class="publish-btn">
          发布
        </u-button>
      </view>
    </view>
  </view>
</template>

<script>
import { savePosts } from '@/api/dynamic.js'
import request from '@/common/request.js'
import { mapGetters, mapState } from 'vuex';
export default {
  name: 'PublishDynamic',
  data() {
    return {
      form: {
        content: '',
        visible: true,
        area_id: '',
        images: []
      },
      cityName: '',
      imageUrls: [],
      isSubmitting: false
    }
  },
  computed: {
    ...mapGetters(['getUserInfo']),
    ...mapState({
      globalConfig: state => state.config,
      userLocation: state => state.location,
    })
  },
  onShow() {
    // 读取缓存中的城市信息设置默认地址
    const cachedCity = uni.getStorageSync('selectedCity');
    if (cachedCity) {
      this.form.area_id = cachedCity.id;
      this.cityName = cachedCity.name;
    }
  },
  methods: {
    chooseCity() {
      // 跳转到城市选择页面，假设返回 { area_id, city_name }
      uni.navigateTo({
        url: '/pages/city/select',
        events: {
          selectCity: (data) => {
            this.form.area_id = data.area_id
            this.cityName = data.city_name
          }
        }
      })
    },
    goBack() {
      uni.navigateBack();
    },
    chooseCity() {
      // 跳转到城市选择页面，假设返回 { area_id, city_name }
      uni.navigateTo({
        url: '/pages/city/select',
        events: {
          selectCity: (data) => {
            this.form.area_id = data.area_id
            this.cityName = data.city_name
          }
        }
      })
    },
    clearCity() {
      this.form.area_id = '';
      this.cityName = '';
    },
    chooseImage() {
      // 选择图片
      uni.chooseImage({
        count: 9 - this.imageUrls.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          uni.showLoading({ title: '上传中...' });
          this.uploadImages(res.tempFilePaths)
            .then(urls => {
              this.imageUrls = [...this.imageUrls, ...urls];
              this.form.images = [...this.form.images, ...urls];
              uni.showToast({ title: '图片上传成功', icon: 'success' });
            })
            .catch(error => {
              uni.showToast({ title: error.message || '图片上传失败', icon: 'none' });
            })
            .finally(() => {
              uni.hideLoading();
            });
        }
      })
    },
    uploadImages(tempFilePaths) {
      return new Promise((resolve, reject) => {
        const uploadPromises = tempFilePaths.map(tempPath => {
          return new Promise((innerResolve, innerReject) => {
            uni.uploadFile({
              url: request.baseUrl + '/api/user/upload',
              filePath: tempPath,
              name: 'file',
              header: {
                token: uni.getStorageSync('token')
              },
              success: (uploadRes) => {
                try {
                  const data = JSON.parse(uploadRes.data);
                  if (uploadRes.statusCode === 200 && data.code === 1) {
                    innerResolve(data.data.image);
                  } else {
                    innerReject(new Error(data.msg || '图片上传失败'));
                  }
                } catch (e) {
                  innerReject(new Error('解析上传结果失败'));
                }
              },
              fail: () => {
                innerReject(new Error('网络请求失败，请检查网络连接'));
              }
            });
          });
        });

        Promise.all(uploadPromises)
          .then(urls => resolve(urls))
          .catch(error => reject(error));
      });
    },
    deleteImage(index) {
      this.imageUrls.splice(index, 1)
      this.form.images.splice(index, 1)
    },
    chooseEmoji() {
      // 选择表情逻辑
      uni.showToast({ title: '表情功能待实现', icon: 'none' })
    },
    async submit() {
      // 表单验证
      if (!this.form.content && this.form.images.length === 0) {
        return uni.showToast({ title: '内容和图片不能同时为空', icon: 'none' })
      }
      if (!this.form.area_id) {
        return uni.showToast({ title: '请选择城市', icon: 'none' })
      }

      this.isSubmitting = true
      try {
        // 准备接口参数
        const params = {
          info: this.form.content,
          images: this.form.images.join(','),
          is_show: this.form.visible ? '1' : '2',
          area_id: this.form.area_id
        }

        const res = await savePosts(params)
        console.log(res, 'savePosts');
        console.log(res.data, 'data');
        console.log(res.data.code, 'code');
        
        
        if (res.data && res.data.code === 1) {
          uni.showToast({ title: '发布成功', icon: 'success' })
          uni.navigateBack()
        } else {
          uni.showToast({ title: res.msg || '发布失败', icon: 'none' })
        }
      } catch (error) {
        console.log(error);
        
        uni.showToast({ title: '网络错误，发布失败', error })
      } finally {
        this.isSubmitting = false
      }
    }
  }
}
</script>

<style scoped>
.publish-container { min-height: 100vh; background: #f8f8f8; padding-bottom: 20rpx; }
.top-bar { display: flex; align-items: center; padding: 32rpx; background: #fff; }
.title { font-size: 36rpx; font-weight: bold; margin-left: 24rpx; flex: 1; text-align: center; }
.form-section { margin: 24rpx 32rpx; padding-top: 30rpx;}
/* .content-input { height: 300rpx; background: #fff; padding: 24rpx; border-radius: 16rpx; } */
.image-preview { display: flex; flex-wrap: wrap; gap: 16rpx; margin: 24rpx 0; }
.preview-item { position: relative; width: 160rpx; height: 160rpx; border-radius: 12rpx; overflow: hidden; }
.preview-img { width: 100%; height: 100%; }
.delete-img { position: absolute; top: 8rpx; right: 8rpx; background: rgba(0,0,0,0.5); border-radius: 50%; }
.form-row { display: flex; align-items: center; gap: 24rpx; margin-top: 16rpx; padding: 24rpx; background: #fff; border-radius: 16rpx; }
.city-tag { flex: 1; text-align: left; }
.icon-btn { padding: 12rpx; }
.switch-label { font-size: 26rpx; color: #888; margin-left: 8rpx; }
.publish-btn { margin-top: 32rpx; height: 90rpx; font-size: 32rpx; background: linear-gradient(90deg, #7b61ff, #c058f3); }
  .publish-bg {
    min-height: 100vh;
    background: #18181a;
    color: #fff;
    padding-bottom: 32rpx;
  }
  .top-bar {
    display: flex;
    align-items: center;
    padding: 32rpx 24rpx 0 24rpx;
    background: transparent;
    height: 80rpx;
  }
  .nav-title {
    flex: 1;
    text-align: center;
    font-size: 36rpx;
    font-weight: bold;
    color: #fff;
    letter-spacing: 2rpx;
  }
  .form-section {
    margin: 24rpx 32rpx;
  }
  /* .content-input {
    height: 220rpx;
    background: #23232b !important;
    padding: 24rpx;
    border-radius: 16rpx;
    color: #fff;
    font-size: 30rpx;
    margin-bottom: 16rpx;
    border: none;
  } */
  .dark-input ::v-deep .u-input__textarea { 
    color: #fff !important;
    font-size: 30rpx;
     height: 220rpx;
    background: #23232b !important;
     padding: 24rpx;
    border-radius: 16rpx;
     color: #fff;

  }
  .image-preview {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
    margin: 24rpx 0 0 0;
  }
  .preview-item {
    position: relative;
    width: 120rpx;
    height: 120rpx;
    border-radius: 12rpx;
    overflow: hidden;
    background: #23232b;
    border: 1rpx solid #23232b;
  }
  .preview-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 12rpx;
    background: #23232b;
  }
  .delete-img-btn {
    position: absolute;
    top: 6rpx;
    right: 6rpx;
    width: 32rpx;
    height: 32rpx;
    background: rgba(0,0,0,0.5);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 2;
  }
  .form-row {
    display: flex;
    align-items: center;
    gap: 18rpx;
    margin-top: 24rpx;
    padding: 0;
    background: transparent;
    border-radius: 0;
  }
  .icon-btn {
    width: 48rpx;
    height: 48rpx;
    background: #23232b;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 8rpx;
    cursor: pointer;
  }
  .switch-box {
    display: flex;
    align-items: center;
    gap: 8rpx;
    margin-left: auto;
  }
  .switch-label {
    font-size: 24rpx;
    color: #fff;
    margin-left: 8rpx;
  }
  .publish-btn-box {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 32rpx;
    display: flex;
    justify-content: center;
    z-index: 10;
    pointer-events: auto;
  }
  .publish-btn {
    width: 90vw;
    height: 90rpx;
    font-size: 32rpx;
    border-radius: 48rpx;
    background: linear-gradient(90deg, #7bdffe, #b97cff);
    color: #fff !important;
    box-shadow: 0 4rpx 24rpx 0 rgba(0,0,0,0.12);
    border: none;
  }
</style>
